<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Collection;

class AdminPermission extends BaseModel
{
    use HasFactory;

    public static function getPermissionTree(): array
    {
        $all = self::query()->orderBy('sort')->get();
        return self::getTree($all, null);
    }

    private static function getTree(Collection $permissions, $parentId): array
    {
        $list = [];
        foreach ($permissions->where('parent_id', $parentId) as $permission) {
            $tmp = [];
            $tmp['value'] = $permission->id;
            $tmp['label'] = $permission->name;
            $tmp['children'] = self::getTree($permissions, $permission->id);
            $list[] = $tmp;
        }
        return $list;
    }
}
